/// Platinum Net TCPChatClient.cpp : Chat client used to test TCP Connection class.

#include <sstream>
#include <iostream>
#include "platinum.h"


#define DEFAULTPORT 12345

int ProcessError(Platinum::Error e)
{
	std::cout <<"Error "<< e.errCode << ": " << e.errMessage << "\n";
	return(0);
}

int main(int argc, char* argv[])
{
	int iPort;
	bool quit = false;
	std::string IP,msg;
	std::stringstream mybuf;
	using namespace Platinum::Net;
	if(argc >= 2)
	{
		IP = argv[1];
		if(argc >=3)
		{
			mybuf << argv[2]; 
	    		mybuf >> iPort;
		}else{
			iPort = DEFAULTPORT;
		}
		TCP::Connection* MyConn = new TCP::Connection();
		try{
#ifdef DEBUG
			std::cout << "Initializing Connection\n";
#endif
			TCP::Initialize(MyConn);
#ifdef DEBUG
			std::cout << "Attempting connection to "<< IP <<" on port " << iPort << std::endl;
#endif
			TCP::Connect(MyConn,IP,iPort);
#ifdef DEBUG
			std::cout  << "Connection succesful, now entering interactive mode\n Type /quit to exit chat" << std::endl;
#endif
			TCP::SetBlocking(MyConn,false);

		}catch(Platinum::Error e){
			ProcessError(e);
			quit = true;
		}

		while(!quit)
		{
			try{
				msg = TCP::Recv(MyConn);
				std::cout << msg;
			}catch(Platinum::Error e){
				ProcessError(e);
				quit = true;
			}
               std::getline(std::cin, msg, '\n');

			if(msg == "/quit")
				quit = true;
			try{
				TCP::Send(MyConn,msg);
			}catch(Platinum::Error e){
				ProcessError(e);
				quit = true;
			}

		}
	}
}

